#include "GrayscaleReconstructDialog.h"

GrayscaleReconstructDialog::GrayscaleReconstructDialog(QWidget *parent)
	: AbstractDialog(parent), _pCurAction (new GrayscaleReconstructAction)
{
	ui.setupUi(this);
	ui.cbOperation->addItem (tr ("OBR"));
	ui.cbOperation->addItem (tr ("CBR"));
}



void GrayscaleReconstructDialog::_openEvent ()
{
	_pCurAction = new GrayscaleReconstructAction;
	__pWork->getDoc ()->openPreview (_pCurAction.cvt< AbstractAction > ());
	_pCurAction->startAction (__pWork);
	structElemTextChanged ();
	_pCurAction->setActionType (ui.cbOperation->currentIndex ());
	//ui.txStructElem->setText ("");
	//operationChanged (0);
}



void GrayscaleReconstructDialog::_closeEvent (int r)
{
	if (r == QDialog::Accepted)
		_pCurAction->applyAction ();
	else
		_pCurAction->rejectAction ();
	__pWork->getDoc ()->closePreview ();
	emit repaintViewport ();
}



void GrayscaleReconstructDialog::structElemTextChanged ()
{
	vector< int > numbers;
	QString strStructElem = ui.txStructElem->toPlainText ();

	QStringList rows = strStructElem.split ('\n');
	int rowNum = 0;
	int columnNum = -1;

	for (QStringList::iterator i = rows.begin(); i != rows.end(); ++i)
	{
		if (i->isEmpty ()) continue;
		QStringList aRow = i->split (' ');
		++rowNum;
		int curColumns = 0;

		for (QStringList::iterator j = aRow.begin(); j != aRow.end(); ++j)
		{
			if (j->isEmpty ()) continue;
			bool isInt = false;
			int number = j->toInt (&isInt);
			if (!isInt)
				return;
			numbers.push_back (number);
			++curColumns;
		}
		numbers.push_back (-1); // signal for end of a row
		if (columnNum < curColumns) columnNum = curColumns;
	}

	if (rowNum == 0 || columnNum == 0)
		return;

	Core< int > structElem (QSize (columnNum, rowNum), 
		QPoint (columnNum / 2, rowNum / 2));
	int index = 0;
	for (int j = 0; j < rowNum; ++j)
	{
		for (int i = 0; i < columnNum; ++i)
		{
			if (numbers[index] != -1)
			{
				structElem (i, j) = numbers[index];
				++index;
			}
			else // fill zero
			{
				structElem (i, j) = 0;
			}
		}
		if (numbers[index] == -1) ++index; // skip the end-row signal
	}

	_pCurAction->setStructElem (structElem);

	emit repaintViewport ();
}



void GrayscaleReconstructDialog::operationChanged (int opIndex)
{
	_pCurAction->setActionType (opIndex);
	emit repaintViewport ();
}
